package com.ty.bigevent.controller;

import com.ty.bigevent.model.entry.User;
import com.ty.bigevent.service.UserService;
import com.ty.bigevent.utils.Result;
import com.ty.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
@AllArgsConstructor
@Validated
public class userController {
    private final UserService userService;
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 用户注册
     * @param username 用户名
     * @param password 密码
     * @return Result
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^[a-zA-Z0-9_-]{5,16}$", message = "用户名格式错误") String username,
                           @Pattern(regexp = "^[a-zA-Z0-9_-]{5,16}$", message = "用户名格式错误") String password) {
        log.info("用户注册");
        // 判断用户名是否已经存在
        User user = userService.findByUsername(username);
        if (user != null){
            return Result.error("用户名已存在");
        }
        // 注册用户
        userService.register(username, password);
        return Result.success();
    }
    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return Result
     */
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^[a-zA-Z0-9_-]{5,16}$", message = "用户名格式错误") String username,
                       @Pattern(regexp = "^[a-zA-Z0-9_-]{5,16}$", message = "用户名格式错误") String password) {
        log.info("用户登录");
        // 获取用户
        User user = userService.findByUsername(username);
        if (user == null){
            return Result.error("用户不存在");
        }
        String token = userService.login(username, password);
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.set(token,token,12, TimeUnit.HOURS);
        return Result.success(token);
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/userInfo")
    public Result userInfo() {
        log.info("获取用户信息");
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUsername(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        log.info("更新用户信息");
        // 判断是否为本人
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        if (!userId.equals(user.getId())){
            return Result.error("无权限");
        }
        // 更新用户
        userService.updateUser(user);
        return Result.success();
    }
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@URL @RequestParam String avatarUrl) {
        log.info("更新用户头像");
        // avatarUrl不能为空或者空字符
        if (avatarUrl == null || avatarUrl.length() == 0){
            return Result.error("头像不能为空");
        }
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        userService.updateUserAvatar(userId,avatarUrl);
        return Result.success();
    }
    @PatchMapping("/updatePwd")
    public Result updatePassword(@RequestBody Map<String, String> params,@RequestHeader("Authorization") String token) {
        log.info("更新用户密码");
        String oldPassword = params.get("old_pwd");
        String newPassword = params.get("new_pwd");
        String rePassword = params.get("re_pwd");
        if (!newPassword.equals(rePassword)){
            return Result.error("两次密码不一致");
        }
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        userService.updatePassword(userId,oldPassword,newPassword);
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.getOperations().delete(token);
        return Result.success();
    }
}
